﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Webkit;
using LinkNote.Core;
using net.sgoliver;
using Android.Util;
using Android.Bluetooth;
using LinkNote.Model;

namespace LinkNote
{
    [Activity(Label = "查看笔记")]
    public class NoteViewActivity : LinearLayout
    {
        private TextView txtTitle;
        private TextView txtAuthor;
        private TextView txtSource;
        private TextView txtCreateTime;
        private TextView txtModifyTime;
        private TextView txtLabel;
        private RichTextEditor richeditor;

        public NoteViewActivity(Context context) : base(context)
        {
            init(context, null);
        }

        public NoteViewActivity(Context context, IAttributeSet attrs)
            : base(context, attrs)
        {
            init(context, attrs);
        }

        private LinkNoteFile selectedNote;
        public LinkNoteFile SelectedNote
        {
            get { return selectedNote; }
            set
            {
                selectedNote = value;
                if(selectedNote != null)
                    ShowNoteView(selectedNote);
            }
        }

        public new Activity Context
        {
            get
            {
                return base.Context as Activity;
            }
        }

        private bool fullscreen;
        private void init(Context context, IAttributeSet attrs)
        {
            LayoutInflater li = LayoutInflater.FromContext(context);
            li.Inflate(Resource.Layout.noteview, this, true);

            // Create your application here
            txtTitle = this.FindViewById<TextView>(Resource.Id.txtTitle);
            txtAuthor = this.FindViewById<TextView>(Resource.Id.txtAuthor);
            txtSource = this.FindViewById<TextView>(Resource.Id.txtSource);
            txtCreateTime = this.FindViewById<TextView>(Resource.Id.txtCreateTime);
            txtModifyTime = this.FindViewById<TextView>(Resource.Id.txtModifyTime);
            txtLabel = this.FindViewById<TextView>(Resource.Id.txtLabel);
            richeditor = this.FindViewById<RichTextEditor>(Resource.Id.richeditor);

            //修改笔记
            ImageButton btn = this.FindViewById<ImageButton>(Resource.Id.btnEditNote);
            btn.Click += delegate
            {
                ShowEditView(SelectedNote);
            };
            //打印笔记
            btn = this.FindViewById<ImageButton>(Resource.Id.btnPrintNote);
            btn.Click += delegate
            {
                //相当难搞
                //print();
            };
            //删除笔记
            btn = this.FindViewById<ImageButton>(Resource.Id.btnDelNote);
            btn.Click += delegate
            {
                ExecuteDelete(SelectedNote);
            };
            //全屏查看
            btn = this.FindViewById<ImageButton>(Resource.Id.btnFullScreen);
            if (attrs != null)
            {
                fullscreen = attrs.GetAttributeBooleanValue(null, "fullscreen", false);
                if(fullscreen)
                    btn.SetImageResource(Resource.Drawable.fullscreen_);
            }
            btn.Click += delegate
            {
                if(!fullscreen)
                    ViewFullScreen();
                else
                    this.Context.Finish();
            };
            //更多菜单
            btn = this.FindViewById<ImageButton>(Resource.Id.btnMore);
            this.Context.RegisterForContextMenu(btn);
            btn.Click += delegate
            {
                btn.ShowContextMenu();
            };

            ////笔记本
            //Button noteClassButton = FindViewById<Button>(Resource.Id.btnNoteClass);
            //noteClassButton.Click += (v, e) =>
            //{
            //    NoteViewActivity.ShowClassChooseDialog(this.Context, this.SelectedNote);
            //};

            ////标签
            //Button lableButton = FindViewById<Button>(Resource.Id.btnNoteLabel);
            //lableButton.Click += (v, e) =>
            //{
            //    NoteViewActivity.ShowLabelChooseDialog(this.Context, this.SelectedNote, this);
            //};
        }

        private void ExecuteDelete(LinkNoteFile note)
        {
            string tip = string.Format("是否要删除笔记：{0}", note.title);
            MainActivity.confirmDialog(Context, tip, delegate
            {
                MainActivity ma = MainActivity.Instance;
                ma.DeleteNote(note);

                if (Context is NoteViewFullScreenActivity)
                {
                    this.Context.Finish();
                }
            });
        }

        private void ShowEditView(LinkNoteFile note)
        {
            Intent intent = new Intent();
            intent.SetClass(this.Context, typeof(NoteEditorActivity));
            intent.PutExtra("fileid", note.ID);
            this.Context.StartActivity(intent);
        }

        private void ViewFullScreen()
        {
            Intent intent = new Intent();
            intent.SetClass(this.Context, typeof(NoteViewFullScreenActivity));
            intent.PutExtra("fileid", SelectedNote.ID);
            this.Context.StartActivity(intent);
        }

        private void ShowNoteView(LinkNoteFile file)
        {
            this.FindViewById(Resource.Id.noteViewToolbar).Visibility = file.status == -1 ? ViewStates.Invisible : ViewStates.Visible;
                
            txtTitle.Text = file.title;//data.GetString("title");
            txtAuthor.Text = "作者："+(string.IsNullOrEmpty(file.author)?"(无)":file.author);//data.GetString("author");
            txtSource.Text = "来源："+(string.IsNullOrEmpty(file.source)?"(无)":file.source);//data.GetString("source");
            //string[] tags = file.tags.Split(',');
            //txtAuthor.Text = tags[0];
            //txtSource.Text = tags[1];
            txtCreateTime.Text = "创建时间：" + file.createTime.ToLongDateString() + " " + file.createTime.ToString("HH:mm");//(new DateTime(data.GetLong("createTime"))).ToShortDateString();
            txtModifyTime.Text = "修改时间：" + file.modifyTime.ToLongDateString() + " " + file.modifyTime.ToString("HH:mm");//(new DateTime(data.GetLong("modifyTime"))).ToShortDateString();

            //string labels = "标签：";
            //foreach (NoteLabel l in file.Labels)
            //    labels += l.Name + ",";
            //if (file.Labels.Count > 0)
            //    txtLabel.Text = labels.Remove(labels.Length - 1);
            //else
            //    txtLabel.Text = "标签：（无）";
            txtLabel.Text = "标签：" + (string.IsNullOrEmpty(file.tags)?"(无)":file.tags);
            richeditor.Editable = false;
            richeditor.LoadData(file);
        }

        private LinkNoteFile contexNote;
        public void OnCreateContextMenu(IContextMenu menu, View v, IContextMenuContextMenuInfo info)
        {
            if (v.Id == Resource.Id.btnMore)
            {
                contexNote = SelectedNote;
                MenuInflater inflater = this.Context.MenuInflater;
                inflater.Inflate(Resource.Menu.noteitemcontextmenu, menu);
                menu.SetHeaderTitle("更多操作");
            }
            else if (v.Id == Resource.Id.notelistcell)
            {
                contexNote = v.Tag as LinkNoteFile;
                MenuInflater inflater = this.Context.MenuInflater;
                if(contexNote.status == -1)
                    inflater.Inflate(Resource.Menu.noterecyclemenu, menu);
                else
                    inflater.Inflate(Resource.Menu.noteitemcontextmenu, menu);
                menu.SetHeaderTitle("更多操作");
            }
            richeditor.OnCreateContextMenu(menu, v, info);
        }

        public void OnContextItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                case Resource.Id.mnu_noteitem_delete:
                    ExecuteDelete(contexNote);
                    break;
                case Resource.Id.mnu_noteitem_edit:
                    ShowEditView(contexNote);
                    break;
                case Resource.Id.mnu_noteitem_label:
                    ShowLabelChooseDialog(this.Context, contexNote, delegate
                    {
                        this.SelectedNote = contexNote;
                    });
                    break;
                case Resource.Id.mnu_noteitem_move:
                    ShowClassChooseDialog(this.Context, contexNote);
                    break;
                case Resource.Id.mnu_noteitem_sendemail:
                    sendemail(contexNote.title, contexNote.abstra);
                    break;
                case Resource.Id.mnu_noteitem_restore:
                    int classID = contexNote.ClassID;
                    var nc = DBHelper.sqlitedb.Table<NoteClass>().Where(o=>o.catalogueid==contexNote.ClassID);
                    if (nc == null)
                        classID = 0;
                    //服务器还原笔记本
                    WebQuery.noteRestore(contexNote.noteid, "还原笔记本", delegate(QueryResult result)
                        {
                            if (result.status == "SUCCESS")
                            {
                                contexNote.ClassID = classID;
                                contexNote.status = 0;
                                DBHelper.sqlitedb.InsertOrUpdate(contexNote);

                                MainActivity ma = MainActivity.Instance;
                                ma.ShowNoteList();
                                ma.ShowNoteClass();
                            }
                        });
                    break;
            }
            richeditor.OnContextItemSelected(item);
        }

        private void sendemail(string title, string body)
        {
            var email = new Intent(Android.Content.Intent.ActionSend);
            email.PutExtra(Android.Content.Intent.ExtraEmail, new string[] { });
            //email.PutExtra(Android.Content.Intent.ExtraCc, new string[] { "person3@xamarin.com" });
            email.PutExtra(Android.Content.Intent.ExtraSubject, title);
            email.PutExtra(Android.Content.Intent.ExtraText, body);
            email.SetType("message/rfc822");
            this.Context.StartActivity(email);
        }

        private void print()
        {
            BluetoothAdapter bth = BluetoothAdapter.DefaultAdapter;

            if (!bth.IsEnabled)
                bth.Enable();

            ICollection<BluetoothDevice> bthD = bth.BondedDevices;
            foreach (BluetoothDevice d in bthD)
            {
                if (d.Name == "DPP-250")
                {
                    Java.Util.UUID UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
                    BluetoothSocket s = d.CreateRfcommSocketToServiceRecord(UUID);
                    s.Connect();

                    byte[] buffer = System.Text.Encoding.GetEncoding(0).GetBytes("Teste");

                    this.Context.RunOnUiThread(delegate
                    {
                        IAsyncResult xpto = s.OutputStream.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(delegate { }), State.On);
                        s.Close();
                    });
                }
            }
        }

        public void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            richeditor.OnActivityResult(requestCode, resultCode, data);
        }

        public void OnActivityPause()
        {
            richeditor.OnActivityPause();
        }

        static AlertDialog dlg;
        static public void ShowClassChooseDialog(Context context, LinkNoteFile file)
        {
            int uid = MainActivity.loginUser.userId;
            List<NoteClass> list = DBHelper.sqlitedb.Table<NoteClass>().Where<NoteClass>(c => c.UserID == uid)
                .ToList<NoteClass>();
            int selectedIndex = list.FindIndex(c => c.catalogueid == file.ClassID);
            string[] options = list.ConvertAll<string>(c => { return c.Name; }).ToArray();

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.SetTitle("选择笔记本");
            builder.SetSingleChoiceItems(options, selectedIndex, (sender, arg) =>
            {
                NoteClass c = list[arg.Which];
                WebQuery.UpdateNoteDir(file.noteid, file.ClassID, c.catalogueid, "正在移动笔记", delegate(QueryResult result)
                    {
                        file.ClassID = c.catalogueid;
                        DBHelper.sqlitedb.Update(file);

                        MainActivity ma = MainActivity.Instance;
                        ma.ShowNoteList();
                        ma.ShowNoteClass();

                        dlg.Dismiss();                      
                    });
            });

            dlg = builder.Show();
        }

        static public void ShowLabelChooseDialog(Context context, LinkNoteFile file, EventHandler<DialogClickEventArgs> onClose)
        {
            int uid = MainActivity.loginUser.userId;
            List<NoteLabel> list = DBHelper.sqlitedb.Table<NoteLabel>().Where<NoteLabel>(c => c.UserID == uid)
                .ToList<NoteLabel>();
            string[] options = list.ConvertAll<string>(c => { return c.Name; }).ToArray();

            file.tags += "";
            bool[] checkedlist = new bool[list.Count];
            //List<NoteLabel> list2 = file.Labels;
            string[] list2 = file.tags.Split(',');
            for (int i = 0; i < list.Count; i++)
            {
                //bool ischeck = list2.Exists(l => l.ID == list[i].ID);
                bool ischeck = list2.Contains(list[i].Name);
                checkedlist[i] = ischeck;
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            EditText newlablename = new EditText(context);
            builder.SetTitle("选择标签");
            builder.SetView(newlablename);
            builder.SetMultiChoiceItems(options, checkedlist, (sender, arg) =>
            {
                NoteLabel c = list[arg.Which];
                checkedlist[arg.Which] = arg.IsChecked;
                //if (arg.IsChecked)
                //{
                //    if (!file.Labels.Exists(l => l.ID == c.ID))
                //    {
                //        NoteLabelMap nl = new NoteLabelMap();
                //        nl.NoteID = file.ID;
                //        nl.LabelID = c.ID;
                //        DBHelper.sqlitedb.Insert(nl);
                //    }
                //}
                //else
                //{
                //    NoteLabelMap map = file.LabelMaps.Find(m => m.LabelID == c.ID);
                //    if (map != null)
                //        DBHelper.sqlitedb.Delete(map);
                //}
            });
            builder.SetPositiveButton("关闭", (sender, e) =>
            {
                if (!string.IsNullOrEmpty(newlablename.Text))
                {
                    if(file.tags == null || !file.tags.Contains(newlablename.Text))
                    {
                        NoteLabel nl = new NoteLabel();
                        nl.Name = newlablename.Text;
                        nl.UserID = MainActivity.loginUser.userId;
                        DBHelper.sqlitedb.InsertOrUpdate(nl);
                        file.tags += nl.Name + ",";
                    }
                }
                else
                {
                    string tags = "";
                    for (int i=0; i<checkedlist.Length; i++)
                        if (checkedlist[i])
                            tags += list[i].Name + ",";
                    file.tags = tags;
                }

                DBHelper.sqlitedb.InsertOrUpdate(file);
                onClose(sender, e);
                dlg.Dismiss();
                Toast.MakeText(context, "修改笔记标签成功", ToastLength.Short).Show();
            });
            //builder.SetNegativeButton("取消", delegate
            //{
            //    dlg.Dismiss();
            //});

            dlg = builder.Show();
        }
    }
}